package com.lindenvalley.ch;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.Toast;

import com.lindenvalley.ch.content.Task;
import com.lindenvalley.ch.content.User;
import com.lindenvalley.ch.content.Week;
import com.lindenvalley.ch.network.WorkServer;

public class WochenberichtActivity extends AbstractHomeActivity {	
	
	private final int placeEdit_id = 12345;
	private TextView ausbildView, timeView;
	private EditText bodyView;
	private static final int CLEAR_DIALOG_ID = 1002;
	private static final int PLACE_DIALOG_ID = 1003;
	private static final int TIME_DIALOG_ID = 1006;
	private boolean isCreateEverywhereTask;
	private DialogInterface.OnClickListener cancelButtonListener = new DialogInterface.OnClickListener() {
		
		@Override
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			
		}
	};

	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.wochenbericht);
		isEdit = getIntent().getBooleanExtra(TagesberichtActivity.EDIT_INTENT, false);
		isCreateEverywhereTask = getIntent().getBooleanExtra(TagesberichtActivity.CREATE_EVERYWHERE_INTENT_DATA, false);
		weeks = WorkServer.getInstance().getWeeks();
		if (isEdit){
			ImageView createTaskView = (ImageView)findViewById(R.id.createView);
			createTaskView.setVisibility(View.GONE);
//			weeks = WorkServer.getInstance().getWeeks();
			byte weekIndex =  getIntent().getExtras().getByte(TagesberichtActivity.CUR_WEEK_INTENT_DATA);
			int taskId = (int) getIntent().getExtras().getInt(TagesberichtActivity.CUR_TASK_INTENT_DATA);
			if (weeks != null){
				currentWeek = weeks.getWeek(weekIndex);
				currentTask = currentWeek.getTaskById(taskId);
			}
			currentDayOfWeek = getIntent().getIntExtra(TagesberichtActivity.CUR_DAY_INTENT_DATA, 0);
		}
		initLayout();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}
	
	

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if (isEdit && isFinishing() && currentWeek != null && currentTask.getTaskId() != 0){
			currentWeek.addTask(currentTask);
		}
	}

	public void initLayout() {
		MyClickListener listener = new MyClickListener();
		ImageView btnFelder = (ImageView) findViewById(R.id.felderBtnImage);
		btnFelder.setOnClickListener(listener);
		ImageView btnSave = (ImageView) findViewById(R.id.speichernBtnImage);
		btnSave.setOnClickListener(listener);
		ausbildView = (TextView) findViewById(R.id.ausbildView);
		ausbildView.setOnClickListener(listener);
		timeView = (TextView)findViewById(R.id.timeView);	
		if (timeView != null){
			if (User.COMPLETE_DAY.equals(user.getCompleteTask())){
				timeView.setOnClickListener(listener);
				
				
			} else {
				timeView.setVisibility(View.GONE);
			}
		}
		
		bodyView = (EditText) findViewById(R.id.textViewBody);
		bodyView.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				TextSwitcher ts = (TextSwitcher) findViewById(activeTabId);
				if (ts != null) {
					saveBodyTextToTask(activeTabId);
					changeIconTab(ts);
				}
			}
		});
		setActiveTab(R.id.tatigkeitView);
		initTabIcon();

		super.initLayout();

	}
	
	private void setActiveTab(int tabId) {

		TextSwitcher activeTabView = (TextSwitcher) findViewById(tabId);
		int id = activeTabView.getId();
		if (id != activeTabId) {
			activeTabView.showNext();
			TextSwitcher prevTab = (TextSwitcher) findViewById(activeTabId);
			if (prevTab != null) {
				prevTab.showNext();
			}
			activeTabId = id;
			setBodyText(id);
		}

	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		switch (id) {
		case CLEAR_DIALOG_ID:

			builder.setMessage(R.string.dialog_clear);
			builder.setPositiveButton(R.string.okButton,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							if (currentTask != null) {
								currentTask.clear();
								setBodyText(activeTabId);
								initTabIcon();
//								saveTask();
								if (isCreateEverywhereTask){
//									calendar.set(Calendar.YEAR, value)
								}
								if (application.isOffLineWork() && currentTask.getTaskId() == 0){
									currentTask.settaskID(application.getOfflineTaskId());
									application.decrementOffLineTaskId();
								}
								taskInterface.saveTask(WochenberichtActivity.this, currentTask);
							}

						}
					});
			builder.setNegativeButton(R.string.cancelButton, cancelButtonListener);

			break;
		case PLACE_DIALOG_ID:
			builder.setTitle("Ausbildungsabteilung");
			final EditText placeEdit = new EditText(this);
			placeEdit.setId(placeEdit_id);
			LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,
					LayoutParams.WRAP_CONTENT);
			placeEdit.setLayoutParams(params);
			InputFilter[] FilterArray = new InputFilter[1];
			FilterArray[0] = new InputFilter.LengthFilter(20);
			placeEdit.setFilters(FilterArray);
			builder.setView(placeEdit);
			builder.setPositiveButton(R.string.okButton,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							if (currentTask != null) {
								currentTask.setplace(placeEdit.getText()
										.toString());
								setPlaceText();
								setTimeText();
//								saveTask();
							}

						}
					});
			builder.setNegativeButton(R.string.cancelButton, cancelButtonListener);

			break;
		case TIME_DIALOG_ID:
			builder.setTitle(R.string.timeTextTitle);
			final View dialogTimeView = getLayoutInflater().inflate(R.layout.dialog_time, null);
			final DatePicker datePicker;
			builder.setView(dialogTimeView);
			if (isCreateEverywhereTask){
				datePicker = (DatePicker) dialogTimeView.findViewById(R.id.DatePicker1);
				datePicker.setVisibility(View.VISIBLE);
			} else {
				datePicker = null;
			}
			builder.setPositiveButton(R.string.okButton,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							Spinner hourView = (Spinner)dialogTimeView.findViewById(R.id.spinnerHour);
							Spinner minuteView = (Spinner)dialogTimeView.findViewById(R.id.spinnerMinute);
							String hourValue = (String)hourView.getSelectedItem();
							String minuteValue = (String)minuteView.getSelectedItem();
							String value = hourValue.concat(":").concat(minuteValue);
							if (currentTask != null) {
								currentTask.settasktime(value);
								if (isCreateEverywhereTask && datePicker != null){
									Calendar cal = Calendar.getInstance();
									cal.set(Calendar.YEAR, datePicker.getYear());
									cal.set(Calendar.MONTH, datePicker.getMonth());
									cal.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
									currentTask.setdate(cal.getTimeInMillis());
								}
								setTimeText();
							}

						}
					});
			builder.setNegativeButton(R.string.cancelButton, cancelButtonListener);

			break;
			default:
				return super.onCreateDialog(id);
		}
		return builder.create();
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (resultCode == Activity.RESULT_OK && requestCode == 1) {
			int which = data.getIntExtra(TagesberichtActivity.RESULT_WEEK_DATA, currentWeekIndex);
			setCurrentTaskOfWeek(weeks.getReverseWeek(which));
		} else {
			super.onActivityResult(requestCode, resultCode, data);
		}
		
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case PLACE_DIALOG_ID:
			EditText ev = (EditText) dialog.findViewById(placeEdit_id);
			if (currentTask != null) {
				ev.setText(currentTask.getPlace());
				if (currentTask.getPlace() != null)
					ev.setSelection(currentTask.getPlace().length());
			}
			break;
		case TIME_DIALOG_ID:
			
			if (currentTask != null){
				Spinner hourView = (Spinner)dialog.findViewById(R.id.spinnerHour);
				Spinner minuteView = (Spinner)dialog.findViewById(R.id.spinnerMinute);
				String hour = currentTask.getTaskHour();
				String minutes = currentTask.getTaskMinutes();
				int h = Integer.valueOf(hour);
				int m = Integer.valueOf(minutes)/15;
				hourView.setSelection(h);
				minuteView.setSelection(m);
			}
			
			break;
		default:
			super.onPrepareDialog(id, dialog);
				
		}
		
	}
	
	/**
	 * Set time for task
	 */
	private void setTimeText() {
		if (User.COMPLETE_DAY.equals(user.getCompleteTask())){
			String text;
			if (currentTask.getTaskTime() != null && currentTask.getTaskTime().length() > 0)
				text = String.format(getResources().getString(R.string.timeText), currentTask.getTaskTime());
			else
				text = String.format(getResources().getString(R.string.timeText),"00:00");
			timeView.setText(Html.fromHtml(text));
		}
	}

	/**
	 * Set text for task place
	 */
	protected void setPlaceText() {
		String text;
		if (currentTask.getPlace() != null && currentTask.getPlace().length() > 0){
			text = String.format(getResources().getString(R.string.placeText), "("+ currentTask.getPlace() + ")");
		} else {
			text = String.format(getResources().getString(R.string.placeText),"");
		}
//		String text = getString(R.string.placeText);
//		if (currentTask != null && currentTask.getPlace() != null) {
//			text += "(" + currentTask.getPlace() + ")";
//		}
//		SpannableString spanString = new SpannableString(text);
//		spanString.setSpan(
//				new ForegroundColorSpan(getResources().getColor(
//						android.R.color.black)), 0, PLACE_TEXT.length(),
//				Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		ausbildView.setText(Html.fromHtml(text));
	}
	
	@Override
	public synchronized void setCurrentTaskOfWeek(Week week) {
		if (!isEdit){
			currentWeek = week;
			currentWeekIndex = weeks.getWeekIndexByDate(currentWeek.getStartDate());
			if (currentWeek != null && !currentWeek.isEmpty()) {
				currentTask = currentWeek.getTasks().get(0);
			} else {
				currentTask = null;
			}
		}
		setBodyText(activeTabId);
		setPlaceText();
		setTimeText();
		setSearchViewText();
		initTabIcon();

	}
	
	private void saveBodyTextToTask(int tabId) {
		if (currentTask == null) {
			currentTask = new Task();
			setCurrentDateForTask();
		}
		String bodyText = bodyView.getText().toString();
		switch (tabId) {
		case R.id.tatigkeitView:
			currentTask.settasktext(bodyText);
			break;
		case R.id.berufsschuleView:
			currentTask.setberufsstext(bodyText);
			break;
		case R.id.themenView:
			currentTask.setthementext(bodyText);
			break;
		}

	}
	
	/**
	 * Select active tab on Wochenbericht layout
	 * @param v Selected View
	 */
	public void onClick(View v) {
		setActiveTab(v.getId());
	}
	
	/**
	 * Save text to edited task from body View.
	 * @param tabId Tab id View which select current tab
	 */
	private void setBodyText(int tabId) {
		String text = null;
		switch (tabId) {
		case R.id.tatigkeitView:
			if (currentTask != null && currentTask.getTaskText() != null)
//				text = Html.fromHtml(currentTask.getTaskText());
				text =  currentTask.getTaskText();
			break;
		case R.id.berufsschuleView:
			if (currentTask != null && currentTask.getBerufssText() != null)
//				text = Html.fromHtml(currentTask.getBerufssText());
				text = currentTask.getBerufssText();
			break;
		case R.id.themenView:
			if (currentTask != null && currentTask.getThemenText() != null)
//				text = Html.fromHtml(currentTask.getThemenText());
				text = currentTask.getThemenText();
			break;
		}
		bodyView.setText(text);
		bodyView.setSelection(bodyView.getText().toString().length());

	}
	
	class MyClickListener implements View.OnClickListener{

		@Override
		public void onClick(View v) {
			int id = v.getId();
				switch (id) {
				case R.id.felderBtnImage:
					if (currentTask != null && !currentTask.isEmpty())
						showDialog(CLEAR_DIALOG_ID);
					break;
				case R.id.speichernBtnImage:
					if (currentTask != null){
						if (user.getStartUp() == null){
							showDialog(CHOICE_FIRST_WEEK_DIALOG_ID);
						} else {
							if (isCreateEverywhereTask){
								
							}
							if (application.isOffLineWork() && currentTask.getTaskId() == 0){
								currentTask.settaskID(application.getOfflineTaskId());
								application.decrementOffLineTaskId();
							}
							taskInterface.saveTask(WochenberichtActivity.this, currentTask);
						}
					}
					break;
				case R.id.ausbildView:
					showDialog(PLACE_DIALOG_ID);
					break;
				case R.id.timeView:
					showDialog(TIME_DIALOG_ID);
					break;

				}
		}
		
	}

}
